/*
 * @Author: albert shyttsyj@126.com
 * @Date: 2024-06-24 16:54:53
 * @LastEditors: albert shyttsyj@126.com
 * @LastEditTime: 2024-06-27 20:27:41
 * @FilePath: /sales-assistant-web/src/permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { devicePathConvert, getAccessToken } from '@/utils/auth'
import { isMobile } from '@/utils/index'

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const hasToken = getAccessToken()

    // 不存在token
    if (!hasToken) {
        // 白名单
        if (to.meta?.whitelist || to.matched.find(e => e.meta?.whitelist)) {
            next()
            return
        }

        // 重定向到登录页
        next(`/auth?redirect=${encodeURIComponent(to.fullPath)}`)
        NProgress.done()
        return
    }

    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)

    // 存在token 去授权的话  直接进入首页
    if (to.path === '/auth') {
        next({ path: isMobile() ? '/m' : '/' })
        NProgress.done()
        return
    }

    const hasUser = store.state.user?.id
    if (!hasUser) {
        await store.dispatch('getUserInfo')
        store.dispatch('dict/loadDictDatas')
        store.dispatch('dict/getArea')
        store.dispatch('components/agentConfig')
        const accessRoutes = await store.dispatch('GenerateRoutes')
        // 根据 roles 权限生成可访问的路由表
        router.addRoutes(accessRoutes) // 动态添加可访问路由表

        const newPath = await devicePathConvert(to.path || '')
        if (newPath !== to.path) {
            next({
                path: newPath,
                params: to.params,
                query: to.query,
                replace: true
            })
            return
        }

        next({
            ...to,
            replace: true
        })
        return
    }

    next()
})

router.afterEach(() => {
    NProgress.done()
})
